
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
import java.util.Scanner;
import java.util.stream.Stream;

public class SideBarTool {

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入文档名称：");
        String name = scanner.nextLine();
        File path = Paths.get(System.getProperty("user.dir"), name).toFile();

        // 列出所有文件和子目录
        StringBuilder stringBuilder = printFiles(path.listFiles(), path, 0, path.getPath());
        System.out.println(stringBuilder);
        Files.writeString(new File(path + "/_sidebar.md").toPath(),
                stringBuilder.toString(), StandardOpenOption.CREATE);
    }

    static StringBuilder printFiles(File[] files, File pf, int level, String prefix) {
        Stream<File> sorted = Arrays.stream(Objects.requireNonNull(files)).filter(
                item -> item.isDirectory()
                        && !item.getName().equalsIgnoreCase("code")
                        && !item.getName().equalsIgnoreCase("assets")
                        && !item.getName().equalsIgnoreCase(".idea")
        ).sorted(Comparator.comparing(o -> {
            if (!o.getName().contains(".")) {
                return 1;
            }
            return Integer.parseInt(o.getName().split("\\.")[0]);
        }));
        files = sorted.toArray(File[]::new);
        level++;
        StringBuilder lineStr = new StringBuilder();
        if (level >= 1) {
            if (level > 2) {
                lineStr.append("    ".repeat(level - 2));
            }
            String pfPath = pf.getPath();
            pfPath = pfPath.replace(prefix + File.separator, "");
            pfPath = pfPath.replaceAll("\\\\","/");
            lineStr.append("* [").append(pf.getName());
            if (level == 1) {
                lineStr.append("简介");
            }
            lineStr.append("](");
            if (level != 1) {
                lineStr.append(pfPath);
            }
            lineStr.append("/)\n");
        }
        for (File f : files) {
            if (f.isDirectory()) {
                lineStr.append(printFiles(f.listFiles(), f, level, prefix));
            }
        }
        return lineStr;
    }
}
